package com.tang.websocket.spring;

import com.tang.websocket.ConfigTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author Tang
 * @classname SimpleWebSocket1
 * @description [ https://www.cnblogs.com/kiwifly/p/11729304.html ,多例的]
 * @date 2021/9/26 15:02
 */
@Component
public class SimpleWebSocket1 extends TextWebSocketHandler {

    private static ConfigTest configTest;

    @Autowired
    public void setConfigTest(ConfigTest configTest) {
        SimpleWebSocket1.configTest = configTest;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        session.getAttributes().forEach((key,value) -> {
            System.out.println("key:" + key + ",value: " + value);
        });
        System.out.println("收到客户端连接为" + session.getUri());
        System.out.println(configTest);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("客户端出错了:" + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("客户端关闭了:" + status.getCode());
    }
}